﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MusicApi.Models;
using System.IO;


namespace MusicApi.Service
{
	/* the real service for handling reading/writing from music files */
	public class SongService : ISongService
	{
		private String _baseDir = @"C:\tmp\";


		private Song mapFile(String file)
		{
			if (file.Contains(".mp3") || file.Contains(".MP3"))
			{
				TagLib.File tagFile = TagLib.File.Create(file);
				if (tagFile.Writeable)
				{
					Song song = new Song();
					song.filename = Path.GetFileName(file);
					song.title = tagFile.Tag.Title;
					song.genre = tagFile.Tag.FirstGenre;
					song.album = tagFile.Tag.Album;
					song.artist = tagFile.Tag.FirstAlbumArtist;

					return song;
				}
				tagFile.Dispose();
			}
			return null;
		}

		/* just for saving the filename to the id3 title tag before renaming 
		 * gets called from handleUploadFiles */
		private void fileNameToTitle(String file)
		{
			try
			{
				bool change = false;
				TagLib.File tagFile = TagLib.File.Create(file);
				if (tagFile.Writeable)
				{
					if (String.IsNullOrEmpty(tagFile.Tag.Title)) /* set "no title" if null */
					{
						tagFile.Tag.Title = Path.GetFileName(file);
						change = true;
					}
					if (String.IsNullOrEmpty(tagFile.Tag.Album))
					{
						tagFile.Tag.Album = "-";
						change = true;
					}

					if (String.IsNullOrEmpty(tagFile.Tag.FirstAlbumArtist))
					{
						if (!tagFile.Tag.AlbumArtists.IsReadOnly)
						{
							tagFile.Tag.AlbumArtists[0] = "-";
							change = true;
						}
					}

					if (change == true)
						tagFile.Save();
				}
				tagFile.Dispose();
			}
			catch (Exception ex)
			{
				Console.WriteLine(String.Format("Error in fileNameToTitle: \n{0}", ex.StackTrace));
			}
		}


		public IEnumerable<Models.Song> GetAllSongs()
		{
			List<Song> songs = new List<Song>();
			try
			{
				String[] files = Directory.GetFiles(_baseDir);
				foreach (var file in files)
				{
					Song song = this.mapFile(file);
					if (song != null)
					{
						songs.Add(song);
					}

				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(String.Format("Error: reading mp3 files from directory: {0}\nError:{1} ", _baseDir, ex.Message));
			}
			return songs;
		}

		public IEnumerable<Models.Song> GetSongByTitle(string title)
		{
			throw new NotImplementedException();
		}

		public IEnumerable<Models.Song> GetSongsByArtist(string artist)
		{
			throw new NotImplementedException();
		}


		public string GetMusicFileDir()
		{
			return _baseDir;
		}

		/* loop through all files in tmp/upload and rename them to a uniq name */
		public void HandleUploadFiles(string path)
		{
			String[] files = Directory.GetFiles(path);
			foreach (var file in files)
			{
				fileNameToTitle(file); /* save the song file name to the id3 tag title before renaming the file */
				File.Move(file, String.Format("{0}{1}{2}", _baseDir, Guid.NewGuid().ToString(), Path.GetExtension(file).ToString()));
			}
		}


		public Song getSongByFilename(string filename)
		{
			return this.mapFile(String.Format("{0}{1}", _baseDir, filename));
		}


		public void HandleUpdateID3(Song song)
		{
			var checkfilenme = _baseDir + song.filename;
			bool change = false;
			TagLib.File tagFile = TagLib.File.Create(checkfilenme);
			TagLib.Id3v2.Tag id3v2tag = tagFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
			if (tagFile.Writeable)
			{
				id3v2tag.Title = song.title;
				id3v2tag.Album = song.album;
				if (!id3v2tag.AlbumArtists.IsReadOnly)
				//	id3v2tag.AlbumArtists[0] = song.artist; //failar alltaf :(
				if (!id3v2tag.Genres.IsReadOnly)
				//	id3v2tag.Genres[0] = song.genre; // failar alltaf :(
				change = true;
			}

			if (change == true)
				tagFile.Save();
			tagFile.Dispose();
		}
	}
}